import yaml
from pathlib import Path
from datetime import datetime


# YAML 文件路径
storage_file = Path("account_data.yaml")


# 初始化存储
def load_storage():
    if not storage_file.exists():
        return {}
    with open(storage_file, "r", encoding="utf-8") as f:
        return yaml.safe_load(f) or {}


def save_storage(data):
    with open(storage_file, "w", encoding="utf-8") as f:
        yaml.dump(data, f, allow_unicode=True, default_flow_style=False)


def track_price_changes(new_data):
    # 加载存储数据
    storage = load_storage()

    added_accounts = []
    price_changed_accounts = []

    for account in new_data:
        account_data = {
            "price": [account[1]],
            "character": account[2],
            "weapon5_num": account[3],
        }

        account_id = account[0]

        if account_id not in storage:
            # 新账号，直接添加
            storage[account_id] = account_data
            added_accounts.append(account_id)
        else:
            # 已存在账号，检查价格是否发生变化
            if account[1] not in storage[account_id]["price"]:
                storage[account_id]["price"].append(account[1])
                price_changed_accounts.append(account_id)

    # 保存更新后的数据
    save_storage(storage)

    return added_accounts, price_changed_accounts


def query_price_trend(
    id: str, show_account_info: bool = False, yaml_file: str = "account_data.yaml"
):
    """查询价格变化趋势

    Args:
        id (str): 账户id
        show_account_info (bool, optional): 是否打印账户信息. Defaults to False.
        yaml_file (str, optional):  Defaults to "account_data.yaml".

    Returns:
        _type_: price_changes, character_info, weapon5_num
    """
    # 读取YAML文件
    with open(yaml_file, "r", encoding="utf-8") as file:
        data = yaml.safe_load(file)

    # 检查id是否存在
    if id in data:
        account_info = data[id]

        # 输出价格变化趋势
        price_changes = account_info["price"]
        print(f"价格变化趋势: {price_changes}")

        # 如果选择打印账户信息，打印相关信息
        if show_account_info:
            character_info = account_info["character"]
            weapon5_num = account_info["weapon5_num"]
            print(f"========账户信息========")
            print(f"ID: {id}, price: {price_changes}")
            print(f"角色: {character_info}")
            print(f"五星武器数量: {weapon5_num}")
        return price_changes, character_info, weapon5_num  
    else:
        print(f"未找到账号ID: {id}")


def price_change_log(changed_accounts, write_to_logs: True):
    """生成价格改变监测文本

    Args:
        changed_accounts (_type_): 账号列表
        write_to_logs (True): 是否写入log文件

    Returns:
        _type_: 价格变化的str
    """
    if not changed_accounts:
        l0 = "WaveCat未检测到价格变化!\n"
    else:
        l0 = "WaveCat监测到下列账号价格发生变化, 请及时关注喵!\n"
        for account_id in changed_accounts:
            price_changes, character_info, weapon5_num = query_price_trend(account_id)
            if len(price_changes) > 1:
                l1 = f"ID: {account_id}价格变动, price: {price_changes[-2]} => {price_changes[-1]}.\n"
            else:
                l1 = f"ID: {account_id}首次上架, price: {price_changes[-1]}.\n"
            l2 = f"角色: {character_info}.\n"
            l3 = f"五星武器数量: {weapon5_num}.\n"
            l4 = "========================\n"
            summary = l1 + l2 + l3 + l4
            l0 += summary
    # 添加时间戳
    current_time = datetime.now()
    # 格式化时间为指定格式
    formatted_time = current_time.strftime("%Y年%m月%d日 %H:%M\n")
    # 添加时间戳到 l0
    l0 += f"{formatted_time}"
    if write_to_logs:
        with open("price_change_log.txt", "a", encoding="utf-8") as f:
            f.write(l0)
    return l0
